package com.ssm.modules.utils;

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.Validate;

import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.SecureRandom;

/**
 * @email: dong980514280@gmail.com
 * @author: Dong
 * @date: 2018/12/20
 * @time: 7:55
 */
public class SecurityUtils {

    private static final String SHA1 = "SHA-1";
    private static final String MD5 = "MD5";

    private static SecureRandom random = new SecureRandom();

    public static final int HASH_INTERATIONS = 1024;
    public static final int SALT_SIZE = 8;


    /**
     *  生成安全的密码，生成随机的 16 位 salt 并经过 HASH_INTERATIONS 次 加密
     */
    public static String entryptPassword(String plainPassword) throws Exception {
        String plain = StringEscapeUtils.unescapeHtml4(plainPassword);
        byte[] salt = generateSalt(SALT_SIZE);
        byte[] hashPassword = digest(plain.getBytes(), SHA1, salt, HASH_INTERATIONS);
        return encodeHex(salt) + encodeHex(hashPassword);
    }

    /**
     * 验证密码
     * @param plainPassword 明文密码
     * @param password 密文密码
     * @return 验证成功返回true
     */
    public static boolean validatePassword(String plainPassword, String password) throws Exception {
        String plain = StringEscapeUtils.unescapeHtml4(plainPassword);
        byte[] salt = decodeHex(password.substring(0,16));
        byte[] hashPassword = digest(plain.getBytes(), SHA1, salt, HASH_INTERATIONS);
        return password.equals(encodeHex(salt) + encodeHex(hashPassword));
    }

    /**
     * 生成随机的Byte[]作为salt.
     *
     * @param numBytes byte数组的大小
     */
    public static byte[] generateSalt(int numBytes) {
        Validate.isTrue(numBytes > 0, "numBytes argument must be a positive integer (1 or larger)", numBytes);

        byte[] bytes = new byte[numBytes];
        random.nextBytes(bytes);
        return bytes;
    }

    /**
     * 对字符串进行散列, 支持 md5 与 sha1 算法.
     */
    private static byte[] digest(byte[] input, String algorithm, byte[] salt, int iterations) throws Exception {
        try {
            //  获取加密算法实例
            MessageDigest digest = MessageDigest.getInstance(algorithm);

            if (salt != null) {
                digest.update(salt);
            }

            byte[] result = digest.digest(input);

            //  加密 iterations 次
            for (int i = 1; i < iterations; i++) {
                digest.reset();
                result = digest.digest(result);
            }
            return result;
        } catch (GeneralSecurityException e) {
            throw new GeneralSecurityException(e);
        }
    }

    /**
     * Hex编码.
     */
    public static String encodeHex(byte[] input) {
        return new String(Hex.encodeHex(input));
    }

    /**
     * Hex解码.
     */
    public static byte[] decodeHex(String input) throws DecoderException {
        try {
            return Hex.decodeHex(input.toCharArray());
        } catch (DecoderException e) {
            throw new DecoderException(e);
        }
    }

}
